<title>数据填报</title>
<script src="/src/lib/echarts.min.js"></script>
<link href="/src/style/disDataFill.css" rel="stylesheet"/>
<div class="layui-card layadmin-header">
	<div class="layui-breadcrumb" lay-filter="breadcrumb" lay-separator=">">
        <a lay-href=""><i class="layui-icon layui-icon-locate"></i>您当前的位置：</a>
		<a><cite class="first-breadcrumb">减灾司</cite></a>
        <a><cite class="second-breadcrumb">数据填报</cite></a>
        <a><cite class="third-breadcrumb"></cite></a>
	</div>
</div>

<div class="layui-fluid clearfix top-part">
    <div class="layui-row disFillContainer">
        <div class="layui-col-md6">
            <div class="fillLeftBox">
                <div class="formTitle">2020减灾司数据填报</div>
                <form class="layui-form roles-updateHtml-form " id="leftForm" action="" lay-filter="roles-updateHtml-form-group">
                    
               </form>
               <div class="card-header-kq"> 
                <button type="button" class="layui-btn layui-btn-sm layui-btn-save btn-color btn-Leftsaveform T-btn"  lay-filter="btnSave" lay-submit data-target="saveLeft"> 保存 </button> 
                <!-- <button type="button" class="layui-btn layui-btn-sm btn-color layui-btn-submit btn-submitform T-btn" data-target="submitLeft">
                    <i class="layui-icon layui-icon-upload-circle"></i>提交
                </button> -->
                <button class="layui-btn layui-btn-sm btn-color btn-fillperson  T-btn" data-target="fillPerson">指派填报人</button>
                <div class="layui-input-inline fillpersonTxt"> </div> 
            </div>
            </div>
        </div> 
        <div class="layui-col-md6"> 
            <div class="fillRightBox">
                <div class="formTitle"> 
                        <label class="layui-form-label">已填报年份：</label> 
                        <div class="layui-input-inline"> 
                            <!-- <select name="length" class="layui-select" lay-filter="year" id="fillYear"> 
                            </select>   -->
                            <select name="length" class="selectBox" lay-filter="year" id="fillYear"> 
                            </select>  
                        </div>
                </div>
                <form class="layui-form roles-updateHtml-form "  id="rightForm" action="" lay-filter="roles-updateHtml-form-group">
                       
               </form>
                <div class="card-header-kq"> 
                   
                    <button class="layui-btn layui-btn-sm  layui-btn-save btn-color btn-saveform T-btn" data-target="saveRight">保存</button> 
                    <button class="layui-btn layui-btn-sm             btn-color          T-btn" data-target="lookFillRecord">查看填报记录</button>
                    <!-- 填报人：<div class="layui-input-inline fillpersonTxt"> </div> -->
                </div> 
            </div>
        </div> 
    </div>
</div>  
<script>
     
var leftSaveFlag=false,rightSaveFlag=false;
//验证表达式
var valifyObj={
    'int':{
        reg: /^([^0][0-9]+|0)$/,
        text:"整数"
    },
    'decimal':{
        reg: /^(([^0][0-9]+|0)\.([0-9]{1,10})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,10})$)|^(([1-9]+)$)/,
        text:"整数或者小数"
    }
   
} 
//保存的时候提示信息有误
var saveLeftInputTipObj={};
var saveRightInputTipObj={};
layui.use(['admin', 'table', 'element', 'tools', 'upload', 'laytpl', 'laydate', 'form'], function(){
    var table = layui.table,
        element = layui.element,
        $ = layui.jquery,
        admin = layui.admin,
        tools = layui.tools,
        view = layui.view,
        upload = layui.upload,
        laytpl = layui.laytpl,
        router = layui.router(),
        search = router.search,
        laydate = layui.laydate,
        form = layui.form,
        router = layui.router();
    var  layout = ['.formTitle', '.layui-form-label', '.layui-input-inline'];
    function isEmptyObj(obj){
            for(var key in obj){
                return false
            }
            return true
    }
    //点击事件
    $(".T-btn").on("click",function(){ 
        var clickBtn=$(this).data("target")
        switch (clickBtn) {
            case "saveLeft"://左边保存   
                    var saveFormParam={ 
                        data:JSON.stringify(getFormParam("leftForm")),
                        access_token: layui.data('layuiAdmin').access_token
                    } 
                    if(!isEmpty(getFormParam("leftForm"))){
                        if(!leftSaveFlag&&isEmptyObj(saveLeftInputTipObj)){ 
                             saveAndSubmit("FillDataSave",saveFormParam);
                             saveLeftInputTipObj={};
                             leftSaveFlag=true;
                        }else{ 
                            var keyIndex=0;
                            for(var key in saveLeftInputTipObj){
                                if(saveLeftInputTipObj[key]&&keyIndex==0){
                                    layer.msg(key+"字段类型为"+saveLeftInputTipObj[key]+"，请重新输入！",{time:1000})
                                    keyIndex++;
                                } 
                            } 
                        }
                    }else{
                        layer.msg("必填项不能为空，请输入！",{time:1000})
                    }
                break;
            case "submitLeft"://左边提交
            
            break;
            case "fillPerson"://左边指派填报人
            if(!$(this).hasClass("layui-btn-disabled")){  
                
                var leftFormParam=getFormParam("leftForm");
                var taskid = leftFormParam.taskid,
                // review = obj.data.review,
                    text = $(this).find('span').text(),
                    that = this;
                    admin.req({
                        url: 'myapi/DC/api/rest/web/custom/GetAllotUser',
                        data: {
                            // taskid: taskid, 
                            access_token: layui.data('layuiAdmin').access_token
                        },
                        success: function(res){
                            if(res.retcode == 0){
                                var indexLayer = layer.open({
                                    id: 'formFill-assignhtml',
                                    title: '<i class="formFill-icon"></i><span style="color:#FFF;">指派填报人</span>',
                                    offset: '20px',
                                    type: 1,
                                    resize: false,
                                    shadeClose: true,
                                    area: ['600px', '650px'],
                                    success: function(lay, index){
                                        var preMsg = res.data != '无数据' ? tools.removeSamePerson(res.data) : [];
                                        view(this.id).render('./disasterPage/components/chooseFillPerson', {
                                            persentMsg: preMsg,
                                            assignState: text
                                        }).done(function(){  
                                            var preName = [];
                                            if(preMsg && preMsg.length > 0){
                                                layui.each(preMsg, function(index, item){
                                                    preName.push(item.writeusername);
                                                });
                                            }
                                            $(lay).on('click', '.T-confirm', function(){
                                                    preMsg = res.data != '无数据' ? tools.removeSamePerson(res.data) : [];
                                                    var checkName = [],
                                                        checkAllName = [],
                                                        checkAllData = [],
                                                        options = [];
                                                    var units = $(lay).find('#assignName .unit-content');
                                                    layui.each(units, function(index, item){
                                                        var usercode = $(this).data('usercode'),
                                                            certcode = $(this).data('certcode'),
                                                            name = $(this).data('name'),
                                                            deptcode = $(this).data('deptcode'),
                                                            deptname = $(this).data('deptname'),
                                                            deptid = $(this).data('deptid');
                                                        checkName.push(name);
                                                        checkAllData.push({ user_code: usercode, cert_code: certcode, name: name, dept_code: deptcode, dept_name: deptname, dept_id: deptid })
                                                    });
                                                    checkAllName = checkName.concat(preName); 
                                                    checkAllData = checkAllData.concat(preMsg);  
                                                    console.log('checkAllName', checkAllName)
                                                    console.log('checkAllData', checkAllData)
                                                    if(checkAllData &&checkAllData <= 0){
                                                        layer.msg('请选择人员', {time: 1500});
                                                        return ;
                                                    }else{ 
                                                        admin.req({
                                                                url: 'myapi/DC/api/rest/web/custom/AssignFillUser',
                                                                data:{
                                                                    taskid:taskid,
                                                                    // GetFillFields:checkAllName.join(","),
                                                                    persentMsg:JSON.stringify(checkAllData)
                                                                },
                                                                type:"post",
                                                                done: function(res){ 
                                                                    if(res.data.retcode==0){
                                                                        layer.msg(res.data.assign,{time:1000},function(){ 
                                                                            layer.close(indexLayer);
                                                                            initAllData("GetFillFields","leftForm");  
                                                                        })
                                                                    }else{ 
                                                                        layer.msg(res.data.retmsg,{time:1000})
                                                                    }
                                                                },
                                                                error:function(erro){
                                                                    console.log(erro);
                                                                }
                                                    })
                                                        
                                                    }
                                                }) 
                                             }) 
                                     }
                                })
                            }  
                        } 
                }) 
            }
            break;
            case "saveRight"://右边保存
                    
                    var saveFormParam={ 
                        data:JSON.stringify(getFormParam("rightForm")),
                        access_token: layui.data('layuiAdmin').access_token
                    } 
                    if(!isEmpty(getFormParam("rightForm"))){
                        if(!rightSaveFlag&&isEmptyObj(saveRightInputTipObj)){ 
                             saveAndSubmit("FillDataSave",saveFormParam);
                             saveRightInputTipObj={};
                             rightSaveFlag=true;
                        }else{ 
                            var keyIndex2=0;
                            for(var key in saveRightInputTipObj){
                                if(saveRightInputTipObj[key]&&keyIndex2==0){
                                    layer.msg(key+"字段类型为"+saveRightInputTipObj[key]+"，请重新输入！",{time:1000})
                                    keyIndex2++;
                                } 
                            } 
                        }
                    }else{
                        layer.msg("必填项不能为空，请输入！",{time:1000})
                    }
            break;
            case "lookFillRecord"://右边查看填报记录
                var leftFormParam=getFormParam("leftForm");
                admin.req({
					url: 'myapi/DC/api/rest/web/custom/GainHistory',
					data: {
						id: leftFormParam.id
					},
					done: function(res){
						if(res.retcode == '0'){
							if(res.data && res.data.length > 0){
								var taskrecode = layer.open({
									id: 'temporary-addhtml',
									title:'<i class="formFill-icon"></i><span style="color:#FFF;">查看填报记录</span>',
									offset: '110px',
                                    type: 1,
                                    resize: false,
									shadeClose: true,
									area: ['800px', '450px'],
									success: function(lay, index){
										view(this.id).render('./disasterPage/components/disHistory', {history: res.data});
									}
								});
							}else{
								layer.msg('暂无记录', {time: 1500});
							}
						}
					}
				})
            break;
        
            default:
                break;
        }
    })
    //保存提交以及确定接口调用
    function saveAndSubmit(urlTxt,param){
        admin.req({
					url: 'myapi/DC/api/rest/web/custom/'+urlTxt,
					data:param,
                    type:"post",
					done: function(res){ 
                        if(res.data.retcode==0){
                            leftSaveFlag=false;
                            rightSaveFlag=false;
                            layer.msg(res.data.retmsg,{time:1000})
                        }else{
                            leftSaveFlag=false;
                            rightSaveFlag=false;
                            layer.msg(res.data.retmsg,{time:1000})
                        }
                    },
                    error:function(erro){
                        console.log(erro);
                    }
        })

    }
    //表单保存
    // form.on('submit(btnSave)', function (data) {
    //     console.log('object', data)
    //     //表单数据formData
    //     var formData = data.field;
    //     console.log('formData', formData)
    // });
   
    //表单提交
    //初始化数据
    function initAllData(urlTxt,id,taskid){ 
        admin.req({
                url: 'myapi/DC/api/rest/web/custom/'+urlTxt,
                data: {
                    taskid:taskid,
                    access_token: layui.data('layuiAdmin').access_token
                },
                type:"post",
                done: function(res){ 
                    if(res.data.retcode==0){
                        
                        var fillFields=res.data.fillFields;
                        var formBox="";
                        for(var i=0;i<fillFields.length;i++){
                            var eachField=fillFields[i];
                            var itemValue;
                            if(eachField.data_type=="int"||eachField.data_type=="decimal"){
                                itemValue=eachField.column_name_value
                            }else{
                                itemValue=eachField.column_name_value?eachField.column_name_value:" ";
                            }
                            var iemBox="",hideFlag=""; 
                            // var type=eachField.data_type=="int"?"number":"text";
                            var type,placeholder;
                            if(eachField.data_type=="int"||eachField.data_type=="decimal"){
                                type="number";
                                // placeholder='请输入'+valifyObj[eachField.data_type].text
                            }else{
                                type="text"; 
                            }
                            if(eachField.fill=="0"){
                                if(eachField.column_name=="id"||eachField.column_name=="taskid"){
                                    hideFlag="layui-hide";
                                    iemBox='<input inputType='+eachField.data_type+' type='+type+'  name='+eachField.column_name+'   class="layui-input" autocomplete="off" value='+itemValue+' >'
                                    formBox+='<div class="layui-form-item '+hideFlag+'">'+
                                        '<label class="layui-form-label">'+eachField.column_comment+'：</label> '+
                                        '<div class="layui-input-inline"> '+
                                            iemBox+
                                        '</div>'+
                                        '<span class="icon-important">*</span>'+
                                '</div>'
                                } 
                            }else{ 
                                if(eachField.column_name=="memo"){
                                    hideFlag=" ";
                                    iemBox='<textarea inputType='+eachField.data_type+' type='+type+'  name='+eachField.column_name+' autocomplete="off"   class="layui-textarea" >'+itemValue+'</textarea>'
                                }else{
                                    iemBox='<input inputType='+eachField.data_type+'  type='+type+'  name='+eachField.column_name+' class="layui-input" autocomplete="off" value='+itemValue+' >'
                                    if(eachField.column_name=="id"||eachField.column_name=="taskid"){
                                        hideFlag="layui-hide";
                                    }else{
                                        hideFlag=" ";
                                    }  
                                }
                                formBox+='<div class="layui-form-item '+hideFlag+'">'+
                                        '<label class="layui-form-label">'+eachField.column_comment+'：</label> '+
                                        '<div class="layui-input-inline"> '+
                                            iemBox+
                                        '</div>'+
                                        '<span class="icon-important">*</span>'+
                                '</div>'
                            }  
                        }  
                         if(id=="leftForm"){ 
                                var tasknameTxt=res.data.taskname?res.data.taskname:"";
                              $(".fillLeftBox .formTitle").text(tasknameTxt); 
                              if(res.data.exist_type=="02"){
                                $(".btn-fillperson").show();
                                $(".btn-fillperson").text(res.data.assign);
                                if(res.data.assign=="已指派"){
                                    $(".btn-fillperson").addClass("layui-btn-disabled") 
                                }else{
                                    $(".btn-fillperson").removeClass("layui-btn-disabled")
                                }
                                $(".fillpersonTxt").removeClass("layui-hide"); 
                              }else{
                                $(".btn-fillperson").hide();
                                $(".fillpersonTxt").addClass("layui-hide");
                              }
                         }
                         var writeusers=res.data.writeusers;
                        var nameArr=[];
                        if(writeusers&&writeusers.length>0){
                            for(var i=0;i<writeusers.length;i++){
                                nameArr.push(writeusers[i].username)
                            }
                        } 
                        $("#"+id).siblings(".card-header-kq").find(".fillpersonTxt").text(nameArr.join(","));
                        $("#"+id).empty().append(formBox); 
                        tools.setFont(layout);
                    }else{
                        $("#"+id).empty();
                    }
                    
                }
        })
        
    }
     //获取右侧下拉框数据
     function getYearData(){ 
            admin.req({
                    url: 'myapi/DC/api/rest/web/custom/FillDropDown',
                    data: {  
                        access_token: layui.data('layuiAdmin').access_token
                    },
                    done: function(res){ 
                         if(res.data.retcode==0){
                             var selectDataArr=res.data.data;
                             var options="";
                            for(var i=0;i<selectDataArr.length;i++){
                                options+="<option value="+selectDataArr[i].taskid+">"+selectDataArr[i].year+"</option>"
                            }
                            $("#fillYear").empty().append(options);    
                            form.render('select');// 再次渲染select    
                            setTimeout(function(){
                                form.on('select(year)', function (data) { 
                                        initAllData("GetHistoryData","rightForm",data.value);
                                }); 
                                debugger
                                $('#fillYear').siblings("div.layui-form-select").find('dl').eq(0).children("dd").eq(0).click(); 
                            },100)
                           
                         }
                    }
                })  
        }
        
    //获取表单所有数据 
    function getFormParam(id){
        var formArr=$('#'+id).serializeArray();
        var addParam={};
        for(var i=0;i<formArr.length;i++){
            var nameO=formArr[i].name; 
            addParam[formArr[i].name]=formArr[i].value; 
        }
        return addParam;
    }
    //判断表单项是否为空
    function isEmpty(strParam){
        for(var key in strParam){
            var obj=strParam[key]; 
            if(key!="id"){
                if(typeof obj == "undefined" || obj == null || obj == ""){
                return true;
            } 
            } 
           
        }
        return false;   
    }
    //入口函数文件
    function entry(){
        //获取下拉框数据
        getYearData();
        //请求初始化接口数据
        initAllData("GetFillFields","leftForm");  
     
        //事件绑定
         //输入验证操作 
        $(".fillLeftBox").delegate(".layui-input", "blur", function(){ 
            var _thisValue=Number($(this).val()),_thisInputType=$(this).attr("inputType"); 
            var labelTxt=$(this).parents('.layui-input-inline').siblings('label').html();
            if(_thisInputType=="int"||_thisInputType=="decimal"){
                if(!valifyObj[_thisInputType].reg.test(_thisValue)){ 
                    saveLeftInputTipObj[labelTxt]=valifyObj[_thisInputType].text;
                    layer.msg('该列字段类型为'+valifyObj[_thisInputType].text+'格式，请正确输入！', {time: 1500});  
                    leftSaveFlag=true; 
                }else{
                    delete saveLeftInputTipObj[labelTxt];
                    leftSaveFlag=false;
                }
            } 
        });
        //右边
        $(".fillRightBox").delegate(".layui-input", "blur", function(){ 
            var _thisValue=Number($(this).val()),_thisInputType=$(this).attr("inputType");
            var labelTxt=$(this).parents('.layui-input-inline').siblings('label').html();
             
            if(_thisInputType=="int"||_thisInputType=="decimal"){
                if(!valifyObj[_thisInputType].reg.test(_thisValue)){
                    layer.msg('该列字段类型为'+valifyObj[_thisInputType].text+'格式，请正确输入！', {time: 1500}); 
                    saveRightInputTipObj[labelTxt]=valifyObj[_thisInputType].text;
                    rightSaveFlag=true; 
                }else{  
                    delete saveRightInputTipObj[labelTxt];
                    rightSaveFlag=false;
                }
            }
           
        });
    } 
    entry();
   
});
</script>